#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

class Sock
{
private:
public:
    Sock() {}

    static int Socket()
    {
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(2);
        }

        return sockfd;
    }

    static void Bind(int listen_sockfd, uint16_t port)
    {
        struct sockaddr_in local;
        //清空初始化
        memset(&local, 0, sizeof(local));
        //协议家族
        local.sin_family = AF_INET;
        //填充端口号
        local.sin_port = htons(port);
        //接收任何一个ip
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(listen_sockfd, (struct sockaddr *)&local, sizeof(local)) == -1)
        {
            std::cerr << "bind error" << std::endl;
            exit(3);
        }
    }

    static void Listen(int listen_sockfd)
    {
        static const int backlog = 5;
        if (listen(listen_sockfd, backlog) == -1)
        {
            std::cerr << "listen error" << std::endl;
            exit(4);
        }

        std::cout << "listen success..." << std::endl;
    }

    static void Connect(int sockfd, std::string ip, uint16_t port)
    {
        struct sockaddr_in peer;
        bzero(&peer, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        peer.sin_addr.s_addr = inet_addr(ip.c_str());

        if (connect(sockfd, (struct sockaddr *)&peer, sizeof(peer)) == -1)
        {
            std::cerr << "connect error" << std::endl;
            exit(5);
        }

        //连接成功
        std::cout << "connect success..." << std::endl;
    }

    static int Accept(int listen_sockfd)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sockfd;

        if ((sockfd = accept(listen_sockfd, (struct sockaddr *)&peer, &len)) == -1)
        {
            std::cerr << "accept error" << std::endl;
            exit(6);
        }

        //获取端口号
        uint16_t port = ntohs(peer.sin_port);
        std::cout << "get a new link->port: " << port << std::endl;

        return sockfd;
    }

    ~Sock() {}
};